package com.by.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author LittleDesire
 * @description
 * @date 2022-03-24 周四 9:58
 * @since 17
 */
@Controller @RequestMapping("cc")
public class HelloController {

    /**
     * 不加 @ResponseBody spring会去寻找视图层，若没有当前页面，则会报 404 错误
     * @return 字符串 (demo 你好)
     */
    @GetMapping("d1")
    public String demo1() {
        return "demo 你好";
    }

    /**
     * 若是字符串 则直接输入字符串，若是对象，则需要使用jackson转换器转换为字符串
     * @return (demo 你好)
     */
    @GetMapping("d2")
    @ResponseBody
    public String demo2() {
        return "demo 你好";
    }

    /**
     * 若是字符串 则直接输入字符串，若是对象，则需要使用jackson转换器转换为字符串
     * @return (demo 你好)
     */
    @GetMapping("d3")
    @ResponseBody
    public Map<String, Object> demo3(HttpServletRequest req) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", "zhangsan");
        map.put("id", "刻晴");
        map.put("time", LocalDateTime.now());
        map.put("addr", req.getRemoteAddr());
        return map;
    }

    @GetMapping("d4")
    @ResponseBody
    public void demo5(HttpServletRequest req, HttpServletResponse resp, HttpSession session) throws IOException {
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<meta charset=\"utf-8\">");
        out.println("<title>首页</title>");
        out.println("<meta name=\"keywords\" content=\"关键字\">");
        out.println("<meta name=\"description\" content=\"简介\">");
        out.println("</head>");
        out.println("<body>");
        out.println("<h2>"+"req.getServletContext()："+req.getServletContext()+"</h2>");
        out.println("<h2>"+"req.getSession()："+req.getSession()+"</h2>");
        out.println("<h2>"+"session         ："+session+"</h2>");
        out.println("<h2>"+"resp            ："+resp+"</h2>");
        out.println("<h2>"+"req            ："+req+"</h2>");
        out.println("</body>");
        out.println("</html>");
        out.flush();
        out.close();
    }
}
